package com.ileaf.java8;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Lianlb
 * @since 2019-11-16 11:12
 */
public class ListMain {

    public static void main(String[] args) {
        List<Apple> list = new ArrayList<>();
        list.add(new Apple(1, "a1"));
        list.add(new Apple(1, "a2"));
        list.add(new Apple(3, "a4"));
        list.add(new Apple(3, "a3"));
        for (Apple apple : list) {
            System.out.println(apple);
        }
        System.out.println("========== 排序 ==========");
        // 默认升序
        list = list.stream().sorted(Comparator.comparing(Apple::getId)).collect(Collectors.toList());
        // 降序写法
        list = list.stream().sorted((a1, a2) -> a2.getId().compareTo(a1.getId())).collect(Collectors.toList());
        for (Apple apple : list) {
            System.out.println(apple);
        }
        // 空值情况下
//        List<Apple> apples = null;
//        apples = apples.stream().sorted(Comparator.comparing(Apple::getId)).collect(Collectors.toList());
//        for (Apple apple : apples) {
//            System.out.println(apple);
//        }
    }

    static class Apple {
        Integer id;

        String name;

        public Apple(Integer id, String name) {
            this.id = id;
            this.name = name;
        }

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return "Apple{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    '}';
        }
    }
}
